export default class WebSocketService {
  private socket: WebSocket | null = null;
  private url: string; // webSocket地址
  private isOpenHeartCheck: boolean; // 是否开启心跳检查
  private isReconnect: boolean; // 是否开启非正常断线重连
  private heartbeatTimer: number | null = null;
  private heartbeatInterval = 120000; // 心跳检查时间2分钟每次

  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectInterval = 5000; // 5秒
  // 添加一个事件发射器，这里假设我们使用了一个简单的发布/订阅模式
  private eventEmitter: { [event: string]: Array<(data: any) => void> } = {};

  // 订阅事件
  public on(event: string, callback: (data: any) => void) {
    if (!this.eventEmitter[event]) {
      this.eventEmitter[event] = [];
    }
    this.eventEmitter[event].push(callback);
  }

  // 触发事件
  private emit(event: string, data: any) {
    if (this.eventEmitter[event]) {
      this.eventEmitter[event].forEach(callback => callback(data));
    }
  }
  constructor(url: string, isOpenHeartCheck: boolean = true, isReconnect: boolean = true) {
    this.url = url;
    this.isOpenHeartCheck = isOpenHeartCheck;
    this.isReconnect = isReconnect;
  }

  connect() {
    this.socket = new WebSocket(this.url);
    this.socket.onopen = this.onOpen.bind(this);
    this.socket.onmessage = this.onMessage.bind(this);
    this.socket.onclose = this.onClose.bind(this);
    this.socket.onerror = this.onError.bind(this);

    // if (this.isOpenHeartCheck) {
    //   this.startHeartbeat();
    // }
  }

  onOpen() {
    console.log('WebSocket连接已建立');
    this.reconnectAttempts = 0;

    if (this.isOpenHeartCheck) {
      this.startHeartbeat();
    }
  }

  onMessage(event: MessageEvent) {
    const data = JSON.parse(event.data)
    console.log('收到消息:', data);
    this.emit('message', data);
  }

  onClose(event: CloseEvent) {
    if (event.wasClean) {
      console.log('WebSocket连接正常关闭：', event.code, event.reason);
    } else {
      console.error('WebSocket连接意外关闭：', event.code, event.reason);
      if(this.isReconnect){
        this.reconnect();
      }
    }
    if(this.isOpenHeartCheck){
      this.stopHeartbeat();
    }
  }

  onError(error: Event) {
    console.error('WebSocket错误:', error);
  }

  send(data: any) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data));
    } else {
      console.error('WebSocket未连接');
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }


  startHeartbeat() {
    // 先关后开，保证只存在一个
    if (this.heartbeatTimer) {
      return;
    }
    this.heartbeatTimer = setInterval(() => {
      console.log('心跳检查');
      
      this.send({ "active": "heart" });
    }, this.heartbeatInterval);
    console.log('开启心跳检查');

  }

  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
      setTimeout(() => {
        this.connect();
      }, this.reconnectInterval);
    } else {
      console.error('达到最大重连次数，连接失败');
    }
  }

}














// // src/utils/websocket.ts
// import { onUnmounted } from 'vue';

// interface WebSocketOptions {
//   url: string;
//   protocols?: string | string[];
//   reconnectTimeout?: number;
// }

// class WebSocketService {
//   private ws: WebSocket | null = null;
//   private callbacks: { [key: string]: Function[] } = {};
//   private reconnectTimeoutMs: number = 5000; // 默认5秒重连间隔

//   constructor(private options: WebSocketOptions) { }

//   public open(): void {
//     this.ws = new WebSocket(this.options.url, this.options.protocols)
//     this.ws.addEventListener('open', this.handleOpen);
//     this.ws.addEventListener('message', this.handleMessage);
//     this.ws.addEventListener('error', this.handleError);
//     this.ws.addEventListener('close', this.handleClose);
//   }

//   public close(isActiveClose = false): void {
//     console.log('执行关闭连接函数');
//     if (this.ws) {
//       this.ws.close();
//     }
//     // 判断是否为主动关闭
//     if (!isActiveClose) {
//       setTimeout(() => this.reconnect(), this.reconnectTimeoutMs);
//     }
//   }

//   public reconnect(): void {
//     console.log('开始重连');
//     this.open();
//   }

//   public on(event: 'message', callback: (data: any) => void): void;
//   public on(event: 'open' | 'error' | 'close', callback: () => void): void;
//   public on(event: string, callback: (...args: any[]) => void): void {
//     console.log(this.callbacks);

//     if (!this.callbacks[event]) {
//       this.callbacks[event] = [];
//     }
//     this.callbacks[event].push(callback);
//     console.log(this.callbacks);

//   }

//   private handleOpen = (): void => {
//     console.log('WebSocket连接已建立');
//     if (this.callbacks.open) {
//       this.callbacks.open.forEach((cb) => cb());
//     }
//   };

//   private handleMessage = (event: MessageEvent): void => {
//     const data = JSON.parse(event.data);
//     console.log('WebSocket接收到消息:', data);
//     if (this.callbacks.message) {
//       this.callbacks.message.forEach((cb) => cb(data));
//     }
//   };

//   private handleError = (error: Event): void => {
//     console.error('WebSocket错误:', error);
//     if (this.callbacks.error) {
//       this.callbacks.error.forEach((cb) => cb(error));
//     }
//   };

//   private handleClose = (): void => {
//     console.log('WebSocket连接已关闭');
//     // console.log('this.callbacks.close',this.callbacks.close);
//     // console.log('this.options.reconnectTimeout',this.options.reconnectTimeout);

//     if (this.callbacks.close) {
//       this.callbacks.close.forEach((cb) => cb());
//       if (!this.options.reconnectTimeout) {
//         this.reconnect();
//       }
//     }
//   };

//   public send(data: any): void {
//     if (this.ws && this.ws.readyState === WebSocket.OPEN) {
//       this.ws.send(JSON.stringify(data));
//     } else {
//       console.warn('尝试发送消息时WebSocket未连接');
//     }
//   }
// }

// export default function useWebSocket(options: WebSocketOptions) {
//   const wsService = new WebSocketService(options);

//   onUnmounted(() => {
//     wsService.close(true);
//   });

//   return {
//     open: wsService.open.bind(wsService),
//     close: wsService.close.bind(wsService),
//     reconnect: wsService.reconnect.bind(wsService),
//     on: wsService.on.bind(wsService),
//     send: wsService.send.bind(wsService)
//   };
// }


// /* 使用方法



// import useWebSocket from '@/utils/websocket';//引入websocket.ts文件

// import config from '@/config' //引入公共配置文件

// const wsOptions = {
//   url: config.WEB_BASE_URL,
// };

// const { open, close, reconnect, on, send } = useWebSocket(wsOptions);

// onMounted(() => {
//   open();//在onMounted钩子中调用open函数，链接websocket

//   // 注册消息接收处理函数
//   on('message', (data) => {
//     receivedMessage = data;
//     console.log(data)
//   });
// });


// */




